﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using static TaskQueueDemo.Logger;

namespace TaskQueueDemo
{
    public class Program
    {
        private static ConsoleColor GetColor(int index)
        {
            switch (index % 5)
            {
                case 0:
                    return ConsoleColor.Red;
                case 1:
                    return ConsoleColor.Green;
                case 2:
                    return ConsoleColor.Yellow;
                case 3:
                    return ConsoleColor.White;
                case 4:
                    return ConsoleColor.DarkMagenta;
                default:
                    return ConsoleColor.Red;
            }
        }

        static void Main(string[] args)
        {
            // 清除日志
            Clear();
            Console.Clear();
            Console.CursorVisible = false;

            #region 初始化环形队列结构
            // 根据CPU数量，设置线程数
            int threadCount = 2;
            QueueManager<LinkQueue> manager = new(threadCount);
            // 创建头队列
            LinkQueue q1 = new LinkQueue(ConsoleColor.Red);
            manager.AddQueue(q1);
            // 模拟的总队列数量
            int qCount = 3;
            for (int i = 1; i < qCount; i++)
            {
                manager.AddQueue(new LinkQueue(GetColor(i)));
            }

            #endregion

            // 开始执行任务
            manager.Start(q =>
            {
                Print(q);
            }, 2);

            manager.OnEnd += Manager_OnEnd;

            Console.ReadLine();

        }

        private static void Manager_OnEnd()
        {
            Console.CursorTop = 8;
            Console.CursorLeft = 0;
            PrintLog();
        }

        private static object pLock = new object();

        /// <summary>
        /// 控制台打印进度
        /// </summary>
        /// <param name="q"></param>
        private static void Print(LinkQueue q)
        {
            lock (pLock)
            {
                Console.ForegroundColor = q.Color;
                Console.CursorTop = q.Index;
                Console.CursorLeft = 0;
                Console.Write(string.Join("", Enumerable.Repeat("  ", 50)));
                Console.CursorLeft = 0;
                Console.Write($"TID[{ Thread.CurrentThread.ManagedThreadId}]:QName={q.Name}:Current={q.Jobs.Dequeue()}");
                Console.CursorLeft = 30;
                Console.Write($"{string.Join("", Enumerable.Repeat("=", q.Jobs.Count))} Count = {q.Jobs.Count}");
            }
            Thread.Sleep(GetSleepTime(q.Index));
        }

        static Random random = new Random();
        private static int GetSleepTime(int qIndex)
        {
            if (qIndex == 1)
            {
                return 2000;
            }
            return random.Next(100, 200);
        }

    }
}
